<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.png">
  <link rel="mask-icon" href="/images/logo.png" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"gitee.com","root":"/","scheme":"Pisces","version":"7.7.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"./public/search.xml"};
  </script>

  <meta name="description" content="封装ES6之前在ES6之前创建一个类有两种方式。第一种是常见的使用this，第二种是通过类的原型上添加属性和方法。">
<meta property="og:type" content="article">
<meta property="og:title" content="面向对象编程--类的创建，数据的封装">
<meta property="og:url" content="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="共你云雨">
<meta property="og:description" content="封装ES6之前在ES6之前创建一个类有两种方式。第一种是常见的使用this，第二种是通过类的原型上添加属性和方法。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-03-09T08:46:41.003Z">
<meta property="article:modified_time" content="2020-03-09T08:46:42.379Z">
<meta property="article:author" content="Edison">
<meta property="article:tag" content="js">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true
  };
</script>

  <title>面向对象编程--类的创建，数据的封装 | 共你云雨</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>
	<a href="https://github.com/mamba666" target="_blank" rel="noopener" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" style="fill:#151513; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <div>
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">共你云雨</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>


<nav class="site-nav">
  
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
  </ul>

</nav>
</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content">
            

  <div class="posts-expand">
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block " lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/mamba666/mamba666.git/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%BC%96%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Edison">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="共你云雨">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          面向对象编程--类的创建，数据的封装
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>
              

              <time title="创建时间：2020-03-09 16:46:41 / 修改时间：16:46:42" itemprop="dateCreated datePublished" datetime="2020-03-09T16:46:41+08:00">2020-03-09</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/javascript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" itemprop="url" rel="index"><span itemprop="name">javascript设计模式</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="封装"><a href="#封装" class="headerlink" title="封装"></a>封装</h1><h2 id="ES6之前"><a href="#ES6之前" class="headerlink" title="ES6之前"></a>ES6之前</h2><p>在ES6之前创建一个类有两种方式。第一种是常见的使用this，第二种是通过类的原型上添加属性和方法。</p>
<a id="more"></a>
<p>第一种：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Book=<span class="function"><span class="keyword">function</span>(<span class="params">id,bookname,price</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.id=id;</span><br><span class="line">    <span class="keyword">this</span>.bookname=bookname;</span><br><span class="line">    <span class="keyword">this</span>.price=price;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>第二种：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Book.prototype=&#123;</span><br><span class="line">    display:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="通过this和prototype两种方式上的差异"><a href="#通过this和prototype两种方式上的差异" class="headerlink" title="通过this和prototype两种方式上的差异"></a>通过this和prototype两种方式上的差异</h3><p>通过this添加的属性和方法是在当前对象上添加的，但是JS是基于原型的语言，所以，每创建一个对象时，都会有一个原型用于指向其继承的属性和方法。故在使用这些方法时，需要通过对象本身的prototype去一级一级的查找来得到。</p>
<p>即通过this定义的，是该对象本身所拥有的。但是通过prototype定义的，则是通过对象的prototype去访问得到的，故每次通过类创建一个新对象时，这些通过prototype定义的东西是不会再次创建的。</p>
<p>表格中prototype和_proto_指向Book prototype,constructor指向Book。</p>
<p>constructor是一个属性，当创建一个对象时都会为其创建一个原型对象prototype，在prototype对象中又会创建一个constructor属性，那么这个属性指向的就是拥有整个原型对象的对象</p>
<table>
<thead>
<tr>
<th align="center">book</th>
<th align="center">Book</th>
<th align="center">Book prototype</th>
</tr>
</thead>
<tbody><tr>
<td align="center">_proto_</td>
<td align="center">prototype</td>
<td align="center">constructor</td>
</tr>
<tr>
<td align="center">id</td>
<td align="center">id</td>
<td align="center">display</td>
</tr>
<tr>
<td align="center">bookname</td>
<td align="center">bookname</td>
<td align="center"></td>
</tr>
<tr>
<td align="center">price</td>
<td align="center">price</td>
<td align="center"></td>
</tr>
</tbody></table>
<h2 id="ES6"><a href="#ES6" class="headerlink" title="ES6"></a>ES6</h2><p>在ES6中可以直接使用Class创建，继承使用extends，这里不详细讨论ES6语法。</p>
<h2 id="属性与方法封装"><a href="#属性与方法封装" class="headerlink" title="属性与方法封装"></a>属性与方法封装</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Book=<span class="function"><span class="keyword">function</span>(<span class="params">id,name,price</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//私有属性</span></span><br><span class="line">    <span class="keyword">let</span> num=<span class="number">1</span>;</span><br><span class="line">    <span class="comment">//私有方法</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">checkId</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="comment">//特权方法</span></span><br><span class="line">    <span class="keyword">this</span>.getName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="keyword">this</span>.getPrice=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="keyword">this</span>.setName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="keyword">this</span>.setPrice=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="comment">//对象公有属性</span></span><br><span class="line">    <span class="keyword">this</span>.id=id;</span><br><span class="line">    <span class="comment">//对象公有方法</span></span><br><span class="line">    <span class="keyword">this</span>.copy=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;;</span><br><span class="line">    <span class="comment">//构造器</span></span><br><span class="line">    <span class="keyword">this</span>.setName(name);</span><br><span class="line">    <span class="keyword">this</span>.setPrice(price);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>在类的外部通过点语法和通过prototype定义的属性和方法以及上面所写代码进行测试：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Book=<span class="function"><span class="keyword">function</span>(<span class="params">id,bookname,price</span>)</span>&#123;</span><br><span class="line">    <span class="comment">//私有属性</span></span><br><span class="line">    <span class="keyword">let</span> num=<span class="number">1</span>;</span><br><span class="line">    <span class="comment">//私有方法</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">alt</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"xxx"</span>);</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">this</span>.id=id;</span><br><span class="line">    <span class="keyword">this</span>.bookname=bookname;</span><br><span class="line">    <span class="keyword">this</span>.price=price;</span><br><span class="line">    <span class="keyword">this</span>.getId=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="comment">// console.log("new time");</span></span><br><span class="line">        <span class="built_in">console</span>.log(alt());</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//通过点语法添加属性和方法，称为类静态公有属性和方法</span></span><br><span class="line">Book.isChinese=<span class="literal">true</span>;</span><br><span class="line">Book.resetTime=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"new time"</span>);</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">//通过原型添加属性和方法</span></span><br><span class="line">Book.prototype=&#123;</span><br><span class="line">    isJSBook:<span class="literal">false</span>,</span><br><span class="line">    display:<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        alert(<span class="string">"display"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="comment">//TEST</span></span><br><span class="line"><span class="keyword">let</span> b=<span class="keyword">new</span> Book(<span class="number">11</span>,<span class="string">"JS"</span>,<span class="number">100</span>);</span><br><span class="line"><span class="comment">//访问不到类的私有属性</span></span><br><span class="line"><span class="built_in">console</span>.log(b.num);</span><br><span class="line"><span class="comment">//访问不到类的私有方法</span></span><br><span class="line"><span class="built_in">console</span>.log(b.alt);</span><br><span class="line"><span class="comment">//可以访问类的公有属性和方法</span></span><br><span class="line"><span class="built_in">console</span>.log(b.isJSBook);</span><br><span class="line"><span class="built_in">console</span>.log(b.display());</span><br><span class="line"><span class="comment">//访问不到类类静态公有属性</span></span><br><span class="line"><span class="built_in">console</span>.log(b.isChinese);</span><br><span class="line"><span class="comment">//访问不到类静态公有方法</span></span><br><span class="line"><span class="comment">// b.resetTime();</span></span><br><span class="line"><span class="comment">//通过特权方法调用私有变量成功</span></span><br><span class="line">b.getId();</span><br><span class="line"><span class="comment">//直接通过实例化对象调用私有变量失败,通过类直接调用也失败</span></span><br><span class="line"><span class="comment">//b.alt();</span></span><br><span class="line"><span class="comment">// Book.alt();</span></span><br></pre></td></tr></table></figure>

<p>总结：<br>1.私有变量和方法均不能被外面所调用，只能被内部特权方法所调用，故特权方法因此得名。<br>2.类静态公有属性方法对象不能访问。<br>3.通过prototype定义的属性方法可以访问是因为类和实例化的对象的prototype指向的都是同一个对象</p>
<h2 id="闭包实现类的静态变量"><a href="#闭包实现类的静态变量" class="headerlink" title="闭包实现类的静态变量"></a>闭包实现类的静态变量</h2><p>之所以把上述一些js变量和函数称为“静态”，是借用了Java的提法。这些“静态”变量和方法被保存在闭包中，在内存中是唯一的，不会随着该函数副本的增加而增加。如果一个函数需要被实例化多次，但其中的一些内部函数并不需要访问任何实例数据，从节省内存的角度考虑，可采用构建静态函数的方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 闭包</span></span><br><span class="line"><span class="keyword">let</span> Rabbit=(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 静态私有变量</span></span><br><span class="line">    <span class="keyword">let</span> rabbitNum=<span class="number">0</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">myName,myFavoriteFood,myAddress</span>)</span>&#123;</span><br><span class="line">        <span class="comment">// 私有变量</span></span><br><span class="line">        <span class="keyword">let</span> name,</span><br><span class="line">            food,</span><br><span class="line">            address;</span><br><span class="line">        <span class="comment">// 私有方法</span></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">checkPassword</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"password:123"</span>);</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 特权方法</span></span><br><span class="line">        <span class="keyword">this</span>.setName=<span class="function"><span class="keyword">function</span>(<span class="params">newName</span>)</span>&#123;</span><br><span class="line">            name=newName;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> name;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.setFood=<span class="function"><span class="keyword">function</span>(<span class="params">newFood</span>)</span>&#123;</span><br><span class="line">            food=newFood;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getFood=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> food;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.setAddress=<span class="function"><span class="keyword">function</span>(<span class="params">newAddress</span>)</span>&#123;</span><br><span class="line">            address=newAddress;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getAddress=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> address;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.check=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            checkPassword();</span><br><span class="line">        &#125;;</span><br><span class="line">        rabbitNum++;</span><br><span class="line">        <span class="keyword">this</span>.seeNumber=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"rabbitNum="</span>+rabbitNum);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.setName(myName);</span><br><span class="line">        <span class="keyword">this</span>.setFood(myFavoriteFood);</span><br><span class="line">        <span class="keyword">this</span>.setAddress(myAddress);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="comment">// 公有方法</span></span><br><span class="line">Rabbit.prototype.sayHello=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"hello my name is"</span>+<span class="keyword">this</span>.getName());</span><br><span class="line">&#125;</span><br><span class="line">Rabbit.prototype.checkP=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.check();</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 静态公有属性</span></span><br><span class="line">Rabbit.eatBreakfast=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"all rabbits are eating"</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">let</span> rabbit1=<span class="keyword">new</span> Rabbit(<span class="string">"小明"</span>,<span class="string">"牛肉"</span>,<span class="string">"中国"</span>);</span><br><span class="line"><span class="keyword">let</span> rabbit2=<span class="keyword">new</span> Rabbit(<span class="string">"KOBE"</span>,<span class="string">"CHICKEN"</span>,<span class="string">"USA"</span>);</span><br><span class="line"><span class="keyword">let</span> rabbit3=<span class="keyword">new</span> Rabbit(<span class="string">"OBAMA"</span>,<span class="string">"BEEF"</span>,<span class="string">"USA"</span>);</span><br><span class="line">rabbit1.sayHello();</span><br><span class="line">rabbit1.seeNumber();</span><br><span class="line">rabbit2.sayHello();    </span><br><span class="line">rabbit3.sayHello();</span><br></pre></td></tr></table></figure>

<p>这样的写法看起来使通过原型添加的方法和属性脱离了闭包，可以这样修改一下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Rabbit=(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 静态私有变量</span></span><br><span class="line">    <span class="keyword">let</span> rabbitNum=<span class="number">0</span>;</span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">_rabbit</span>(<span class="params">myName,myFavoriteFood,myAddress</span>)</span>&#123;</span><br><span class="line">    	<span class="keyword">let</span> name,</span><br><span class="line">            food,</span><br><span class="line">            address;</span><br><span class="line">        <span class="comment">// 私有方法</span></span><br><span class="line">        <span class="function"><span class="keyword">function</span> <span class="title">checkPassword</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"password:123"</span>);</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="comment">// 特权方法</span></span><br><span class="line">        <span class="keyword">this</span>.setName=<span class="function"><span class="keyword">function</span>(<span class="params">newName</span>)</span>&#123;</span><br><span class="line">            name=newName;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getName=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> name;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.setFood=<span class="function"><span class="keyword">function</span>(<span class="params">newFood</span>)</span>&#123;</span><br><span class="line">            food=newFood;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getFood=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> food;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.setAddress=<span class="function"><span class="keyword">function</span>(<span class="params">newAddress</span>)</span>&#123;</span><br><span class="line">            address=newAddress;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.getAddress=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="keyword">return</span> address;</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">this</span>.check=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            checkPassword();</span><br><span class="line">        &#125;;</span><br><span class="line">        rabbitNum++;</span><br><span class="line">        <span class="keyword">this</span>.seeNumber=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">"rabbitNum="</span>+rabbitNum);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">this</span>.setName(myName);</span><br><span class="line">        <span class="keyword">this</span>.setFood(myFavoriteFood);</span><br><span class="line">        <span class="keyword">this</span>.setAddress(myAddress);</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">// 公有方法</span></span><br><span class="line">	_rabbit.prototype.sayHello=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	    <span class="built_in">console</span>.log(<span class="string">"hello my name is"</span>+<span class="keyword">this</span>.getName());</span><br><span class="line">	&#125;</span><br><span class="line">	_rabbit.prototype.checkP=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	    <span class="keyword">this</span>.check();</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="comment">// 静态公有属性</span></span><br><span class="line">	_rabbit.eatBreakfast=<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	    <span class="built_in">console</span>.log(<span class="string">"all rabbits are eating"</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> _rabbit;</span><br><span class="line">&#125;)();</span><br></pre></td></tr></table></figure>

<h2 id="创建对象的安全模式"><a href="#创建对象的安全模式" class="headerlink" title="创建对象的安全模式"></a>创建对象的安全模式</h2><p>在实例化一个对象时，忘记写上new了会出错。如果没有写的话，实例化的变量是什么呢？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Book=<span class="function"><span class="keyword">function</span>(<span class="params">time,name,price</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">this</span>.time=time;</span><br><span class="line">    <span class="keyword">this</span>.name=name;</span><br><span class="line">    <span class="keyword">this</span>.price=price;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">let</span> b=Book(<span class="string">"2019"</span>,<span class="string">"JS"</span>,<span class="string">"100"</span>);</span><br></pre></td></tr></table></figure>

<p>这段代码没有写new，故肯定不是Book类的一个实例。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//test</span></span><br><span class="line"><span class="built_in">console</span>.log(b);  <span class="comment">//undefined</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="built_in">window</span>.time);  <span class="comment">//2019</span></span><br></pre></td></tr></table></figure>

<p>首先，new关键字的作用可以看做是对当前对象的this的赋值，但是测试中没有使用new，故就会直接执行这个Book的代码，这时，Book的作用域是全局的，所以，当前对象是全局对象window。</p>
<p>稍微修改一下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> Book=<span class="function"><span class="keyword">function</span>(<span class="params">time,name,price</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">if</span>(<span class="keyword">this</span> <span class="keyword">instanceof</span> Book)&#123;</span><br><span class="line">        <span class="keyword">this</span>.time=time;</span><br><span class="line">        <span class="keyword">this</span>.name=name;</span><br><span class="line">        <span class="keyword">this</span>.price=price;</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Book(time,name,price);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>这里使用instanceof来判断当前对象是否为其实例化对象，如果不是，则重新创建这个对象</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/js/" rel="tag"># js</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/03/09/%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/" rel="prev" title="简单工厂模式">
      <i class="fa fa-chevron-left"></i> 简单工厂模式
    </a></div>
      <div class="post-nav-item">
    <a href="/2020/03/09/%E9%9D%A2%E5%90%91%E5%AF%B9%E8%B1%A1%E7%9A%84%E7%A8%8B%E5%BA%8F%E8%AE%BE%E8%AE%A1/" rel="next" title="面向对象的程序设计(基于ES5)">
      面向对象的程序设计(基于ES5) <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  

  </div>


          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#封装"><span class="nav-number">1.</span> <span class="nav-text">封装</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#ES6之前"><span class="nav-number">1.1.</span> <span class="nav-text">ES6之前</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过this和prototype两种方式上的差异"><span class="nav-number">1.1.1.</span> <span class="nav-text">通过this和prototype两种方式上的差异</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#ES6"><span class="nav-number">1.2.</span> <span class="nav-text">ES6</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#属性与方法封装"><span class="nav-number">1.3.</span> <span class="nav-text">属性与方法封装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#闭包实现类的静态变量"><span class="nav-number">1.4.</span> <span class="nav-text">闭包实现类的静态变量</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#创建对象的安全模式"><span class="nav-number">1.5.</span> <span class="nav-text">创建对象的安全模式</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Edison</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">124</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">19</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

<div class="copyright">
</div>
  <div class="powered-by">山高水远  一定相见
  </div>
<div></div>
<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">至今已写107.1k字</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
